import io
import random
from PIL import Image, ImageDraw, ImageFont

# 生成随机字符
def generate_random_code(length):
    code = ""
    characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    for _ in range(length):
        code += random.choice(characters)
    return code

# 生成图形验证码
def generate_captcha(code, width, height, font_path,font_size=None):
    # print("dddddddddddd")
    image = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(image)
    if not font_size:
        font_size = min(width // len(code), height) - 10
    print(font_size)
    font = ImageFont.truetype(font_path, font_size)
    draw.text((5, 5), code, font=font, fill=(0, 0, 0))

    # 添加干扰线
    for _ in range(random.randint(1, 3)):
        x1 = random.randint(0, width // 2)
        y1 = random.randint(0, height)
        x2 = random.randint(width // 2, width)
        y2 = random.randint(0, height)
        draw.line([(x1, y1), (x2, y2)], fill=(0, 0, 0), width=random.randint(1, 2))

    # 添加干扰点
    for _ in range(random.randint(50, 100)):
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.point([(x, y)], fill=(0, 0, 0))

    return image


def generate_captcha_out_strmes_img(w=160,h=50,font_size=36):
    code = generate_random_code(4)  # 生成4位随机验证码
    # if linus:
    # patrh= '/data/www/infirmary_front_admin_api/afast_core/core_tools/ariblk.ttf'
    captcha = generate_captcha(code, width=w, height=h,font_path='ariblk.ttf',font_size=font_size)  # 使用指定字体生成图形验证码
    # captcha.save('captcha.png')  # 保存图形验证码为图片文件
    # 将图片保存到缓存中
    buffer = io.BytesIO()
    captcha.save(buffer, 'PNG')
    # 读取图片的byte值
    image_data = buffer.getvalue()
    buffer.close()
    return code,image_data

# 示例用法


